package com.bnz.user.bnzuser.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.bnz.user.bnzuser.dao.UserDao;
import com.bnz.user.bnzuser.entity.User;
import com.bnz.user.bnzuser.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author xy
 * @date 2022/11/29
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserDao userDao;

    @Override
    public void sendCode(String phone) {
        String code = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set(phone,code);
        Map<String,String> mapData  =  new HashMap<>();
        mapData.put("phone",phone);
        mapData.put("code",code);
        rabbitTemplate.convertAndSend("validcode",mapData);
    }

    @Override
    public boolean isValidCodeSuccess(String phone,String code) {

        String validCode = redisTemplate.opsForValue().get(phone);
        return code.equals(validCode);
    }

    @Override
    public void add(User user) {
        String password = user.getPassword();
        user.setPassword(SecureUtil.md5(password));
        userDao.save(user);
    }
}
